'use client';

import type { IDifference, ISectionClient } from '@/interfaces';
import type { TBody } from '@/types';
import { clientQueryAllSection, createPostTemplate } from '@/services/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import {
  cleanFormData,
  getDiffData,
  getFilterData,
  isEmpty,
  isNum,
} from '@/lib/tool';
import { PostTemplateAdminContext } from '@/contexts/admin/forum/postTemplate';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Editor from '@/app/[locale]/editor/wrapper';

export default function CreatePostTemplateAdminPage() {
  const { show } = useToast();
  const [form, setForm] = useState({
    name: '',
    content: '',
    sectionId: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const context = useContext(PostTemplateAdminContext);
  const queryClient = useQueryClient();
  const metadata = context.metadata!;
  const editorContextRef = useRef<{
    context: any;
    getEditorContent: () => string;
  }>({
    context: undefined,
    getEditorContent: () => '',
  });

  const clientQueryAllSectionQuery = useQuery(
    ['/forum', '/sections', '/client'],
    async () => {
      return (await clientQueryAllSection()) as ISectionClient[];
    },
  );

  const createPostTemplateMutation = useMutation(
    async (
      variables: TBody<{
        name: string;
        content: string;
        sectionId: number;
      }>,
    ) => {
      await createPostTemplate(variables);
    },
  );

  useEffect(() => {
    const differences = diff(
      {
        name: '',
        content: '',
        sectionId: '',
      },
      form,
    );
    setDifferenceData(differences);
  }, [form]);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'DANGER',
          message: '新增帖子模板失败，数据不存在',
        });
        return;
      }

      await createPostTemplateMutation.mutateAsync({
        data: {
          ...(body as any),
          content: getEditorContent(),
        },
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      createPostTemplateMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setForm(cleanFormData(form));
    setDifferenceData([]);
  }

  function checkForm() {
    const { name, content, sectionId } = form;

    if (!name) {
      throw '帖子模板名称不能为空';
    }

    if (!sectionId) {
      throw '未选择版块';
    } else if (!isNum(sectionId)) {
      throw '请正确选择版块';
    }

    if (!getEditorContent()) {
      throw '帖子模板内容不能为空';
    }
  }

  function getEditorContent() {
    return editorContextRef.current.getEditorContent();
  }

  function onChange(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  function onClickReturn() {
    if (typeof context.setIsCreate === 'function') {
      if (context.queryKey) {
        try {
          queryClient.refetchQueries(
            { queryKey: context.queryKey },
            { throwOnError: true },
          );
        } catch (e) {
          show({
            type: 'DANGER',
            message: e,
          });
        }
      }

      context.setIsCreate(false);
    }
  }

  return (
    <div className="row">
      <div className="col">
        <div className="card">
          <div className="card-header bg-transparent text-muted">
            <div className="row row-cols-auto justify-content-between">
              <div className="col">
                <div>
                  <i className="bi bi-plus-lg me-2"></i>
                  新增帖子模板
                </div>
              </div>
              <div className="col">
                <div>
                  <i
                    onClick={onClickReturn}
                    className="bi bi-arrow-return-left cursor-pointer text-primary"
                  ></i>
                </div>
              </div>
            </div>
          </div>

          <div className="card-body">
            <form onSubmit={onSubmit} className="vstack gap-4">
              <div>
                <label className="form-label">名称</label>
                <input
                  type="text"
                  name="name"
                  value={form.name}
                  onChange={onChange}
                  className="form-control"
                  aria-describedby="name"
                  placeholder="请输入帖子模板名称"
                />
              </div>

              <div>
                <label className="form-label">版块</label>
                {clientQueryAllSectionQuery.data && (
                  <select
                    name="sectionId"
                    value={form.sectionId}
                    onChange={onChange}
                    className="form-select"
                    placeholder="请选择版块"
                  >
                    <option disabled value="">
                      请选择版块
                    </option>
                    {clientQueryAllSectionQuery.data.map((item) => {
                      return (
                        <option key={item.id} value={item.id}>
                          {item.name}
                        </option>
                      );
                    })}
                  </select>
                )}

                {clientQueryAllSectionQuery.isError && (
                  <Alert
                    message={clientQueryAllSectionQuery.error}
                    type="error"
                  />
                )}

                {clientQueryAllSectionQuery.isLoading && <AlertLoad />}
              </div>

              {form.sectionId && (
                <div>
                  <label className="form-label">内容</label>
                  <Editor
                    id={form.sectionId}
                    metadata={metadata}
                    type="postTemplate"
                    ref={editorContextRef}
                  />
                </div>
              )}

              <button
                type="submit"
                disabled={createPostTemplateMutation.isLoading}
                className="btn btn-primary w-25 my-4"
              >
                {createPostTemplateMutation.isLoading && (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                )}
                保存
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
